package leetcode;

/**
 * 24. 两两交换链表中的节点
 * 给定一个链表，两两交换其中相邻的节点，并返回交换后的链表。
 * 你不能只是单纯的改变节点内部的值，而是需要实际的进行节点交换。
 * 示例:
 * 给定 1->2->3->4, 你应该返回 2->1->4->3.
 */

public class problems_024 {

    public static void main(String[] arge) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;


        ListNode node11 = null;
        ListNode node21 = new ListNode(0);

        System.out.println(new Solution().swapPairs(node1));
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    static class Solution {
        public ListNode swapPairs(ListNode head) {
            if(null == head) return null;
            ListNode ret = null == head.next ? head : head.next;

            ListNode indexNode = new ListNode(0);
            indexNode.next = head;
            while (null != getNext(indexNode) && null != getNext(getNext(indexNode))) {
                ListNode next1 = indexNode.next;
                ListNode next2 = next1.next;
                // 调换
                next1.next = next2.next;
                next2.next = next1;
                indexNode.next = next2;
                //
                indexNode = next1;
            }
            return ret;
        }
        private ListNode getNext(ListNode node) {
            if (null == node) return null;
            return node.next;
        }
    }
}
